package br.edu.ufcg.ga.parser.args.group;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.ParseException;
import org.jgap.Configuration;
import org.jgap.InvalidConfigurationException;
import org.jgap.impl.TournamentSelector;

public class NStournamentSelectorGroupBuilder extends AbstractMyGroupBuilder {

	private Option NStournamentSelector;
	private Option TStournamentSize;
	private Option TSselectionRate;

	@SuppressWarnings("static-access")
	@Override
	protected void init() {
		NStournamentSelector = OptionBuilder.withDescription("Seleciona os cromossomos disputando um torneio")
				.withLongOpt("NStournamentSelector").create("NS_TS");

		TStournamentSize = OptionBuilder.withDescription("Quantidade de indivíduos a serem considerados no torneio")
				.withLongOpt("TStournamentSize").hasArgs(1).withArgName("n").create("TS_TS");

		TSselectionRate = OptionBuilder
				.withDescription(
						"Probabilidade \"p\" de selecionar o melhor cromossomo no torneio, \"p * (1 - p)\" de selecionar o segundo, \"p * (p * (1 - p))\" o terceiro e assim por diante")
				.withLongOpt("TSselectionRate").hasArgs(1).withArgName("[0, 1]").create("TS_SR");

	}

	@Override
	public void configSafely(Configuration config, CommandLine commandLine) throws InvalidConfigurationException,
			ParseException {
		int tournamentSize = getTournamentSize(commandLine);
		double selectionRate = getProbability(commandLine);
		TournamentSelector ns = new TournamentSelector(config, tournamentSize, selectionRate);

		config.addNaturalSelector(ns, true);
	}

	private double getProbability(CommandLine commandLine) throws ParseException {
		String selectionRateString = getOptionValue(TSselectionRate, commandLine);
		return Double.parseDouble(selectionRateString);
	}

	private int getTournamentSize(CommandLine commandLine) throws ParseException {
		String tournamentSizeString = getOptionValue(TStournamentSize, commandLine);
		return Integer.parseInt(tournamentSizeString);
	}

	@Override
	protected Option getMainOption() {
		return this.NStournamentSelector;
	}

	@Override
	protected Option[] getOtherOptions() {
		return new Option[] {TStournamentSize, TSselectionRate};
	}

}
